package sk.octopuss.archery.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import sk.octopuss.archery.dao.UserDao;
import sk.octopuss.archery.domain.User;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService{
	
	@Autowired
	private UserDao userDao;
	@Autowired 
	private UserAssembler assembler;


	@Override
	@Transactional(readOnly = true)
	  public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException, DataAccessException {
	    final User user = userDao.findByUsername(username);
	    if (user == null) {
			throw new UsernameNotFoundException("user not found");
	    } else {
            if (!user.isActive()) {
                throw new DisabledException("User is disabled");
            }

	    return assembler.buildUserFromUserEntity(user);
	  }
	}
	
}
